<template>
    <div style="width: 100%;">
        <TitleTips title="预算内容" />
        <CardBox v-for="(item, index) in list" :key="index" :title="item.itemName">
            <el-row v-if="item.budgetContent" :gutter="24" class="budget-info">
                <el-col :span="24" class="budget-info-title">
                    {{ item.budgetContent.quarter ? `${item.budgetContent.year}年${item.budgetContent.quarter}季度预算` : `${item.budgetContent.year}年度预算` }}
                </el-col>
                <el-col v-for="m in budgetMap" :key="m.code" :lg="8" :xl="6" class="budget-info-item">
                    <span class="label">{{ m.name }}：</span>
                    <span class="value">{{ getValue(m.code, item.budgetContent) }}</span>
                </el-col>
                <el-col :lg="8" :xl="6" class="budget-info-item">
                    <span class="label">编制说明：</span>
                    <BaseTooltips :text="item.budgetContent.description || ''" class-name="g-line-1" />
                </el-col>
                
            </el-row>
            <el-form ref="form" :model="item" class="size-auto width-100" :rules="rules" :inline="true" size="medium" label-width="90px">
                <el-row :gutter="24">
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="工程量" prop="workAmount">
                            <el-input v-model.trim="item.workAmount" maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="单位" prop="arithmeticalUnit">
                            <el-input v-model.trim="item.arithmeticalUnit" maxlength="50" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="基本费用" prop="basicFee">
                            <el-input v-model.trim="item.basicFee" maxlength="50" show-word-limit clearable placeholder="请输入" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="调整系数" prop="adjustmentFactor">
                            <el-input v-model.trim="item.adjustmentFactor" maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(item)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="预算金额" prop="budgetMoney" :rules="moneyRules(item.budgetContent.remainBudget)">
                            <el-input v-model.trim="item.budgetMoney" disabled maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(index)">
                                <i slot="suffix" class="el-input__icon input-unit">元</i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="编制说明" class="margin-r-0 block-item">
                            <el-input v-model.trim="item.description" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </CardBox>
    </div>
</template>

<script>
import BigNumber from 'bignumber.js'
import { isNumber6 } from '@/utils/validate'
import { MaintenanceProjectConfigModel, BudgetingOldModel } from '@/models' 

export default {
    name: 'FormCard',
    props: {
        form: {
            type: Array,
            default: () => ([])
        },
        type: {
            type: String,
            default: 'add'
        },
        query: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            list: [],
            rules: {
                workAmount: [{ validator: this.validNum, trigger: 'blur' }],
                basicFee: [{ validator: this.validNum, trigger: 'blur' }],
                adjustmentFactor: [{ validator: this.validNum, trigger: 'blur' }]
            },
            model: new MaintenanceProjectConfigModel(),
            budgetingModel: new BudgetingOldModel(),
            projectList: [],
            budgetContent: [],
            budgetMap: [
                { code: 'workAmount', name: '工程量' },
                { code: 'basicFee', name: '基本费用' },
                { code: 'adjustmentFactor', name: '调整系数' },
                { code: 'budgetMoney', name: '预算金额' },
                { code: 'remainBudget', name: '剩余预算' }
            ]
        }
    },
    watch: {
        form: {
            handler(newVal) {
                if (newVal.length > 0) {
                    this.getbudgetContent().then(() => {
                        this.list = newVal.map(item => {
                            let budgetContent = {}
                            this.budgetContent.some(m => {
                                if (m.itemId === item.itemId) {
                                    budgetContent = m
                                    return true
                                }
                            })
                            return {
                                budgetContent,
                                ...item
                            }
                        })
                        // 让父组件的加载动画关闭
                        this.$emit('update:loading', false)
                    })
                }
            },
            // immediate: true,
            deep: true
        }
    },
    created() {
        if (this.type === 'add') {
            this.init()
        }
    },
    methods: {
        init() {
            const template = {
                workAmount: null,
                budgetMoney: null,
                description: null
            }
            this.getbudgetContent().then(() => {
                this.list = this.budgetContent.map(item => {
                    return {
                        budgetContent: item,
                        levelId: item.levelId,
                        levelName: item.levelName,
                        itemId: item.itemId,
                        itemName: item.itemName,
                        content: item.content,
                        arithmeticalUnit: item.arithmeticalUnit,
                        basicFee: item.basicFee,
                        adjustmentFactor: item.adjustmentFactor,
                        ...template
                    }
                }).filter(item => item.budgetContent.workAmount) // 把没预算的空过滤掉
                // 让父组件的加载动画关闭
                this.$emit('update:loading', false)
            })
        },
        getValue(code, item) {
            let res = item[code]
            switch (code) {
                case 'workAmount':
                    res += ' ' + item.arithmeticalUnit
                    break
                case 'budgetMoney':
                    res += ' 元'
                    break
                case 'remainBudget':
                    res += ' 元'
                    break
            }
            return res
        },
        getbudgetContent() {
            return this.budgetingModel.getbudgetContent(this.query).then(res => {
                this.budgetContent = res
            })
        },
        // 针对新建年度养护预算做的计算金额
        handleComputed(item) {
            const a = item['workAmount']
            const b = item['basicFee']
            const c = item['adjustmentFactor']
            // 如果3个值任意一个没有则不处理
            if (!a || !b || !c) { return }
            const value = Number(new BigNumber(a).times(b).times(c).toFixed(6))
            // 更新预算金额
            this.$set(item, 'budgetMoney', value || null)
        },
        handleValidate() {
            const list = []
            const validas = []
            this.$refs['form'].forEach((item, index) => {
                list.push(new Promise(resolve => {
                    item.validate(valida => {
                        validas.push(valida)
                        resolve()
                    })
                })
                )
            })
            return Promise.all([...list]).then(() => {
                const res = !validas.some(item => item === false)
                return res
            }).catch(() => {
                return false
            })
        },
        validNum(rule, value, callback) {
            if (value && !isNumber6(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        validbudgetMoney(rule, value, callback) {
            if (value) {
                if (value > this.remainBudget) {
                    callback(new Error('不能大于剩余预算金额'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        },
        moneyRules(remainBudget) {
            return [{
                validator: (rule, value, callback) => this.validMoney(rule, value, callback, remainBudget),
                trigger: 'change'
            }]
        },
        validMoney(rule, value, callback, remainBudget) {
            if (value) {
                if (value > remainBudget) {
                    callback(new Error('不能大于剩余预算金额'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 100px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
.budget-info {
    .budget-info-title {
        font-size: 14px;
        font-weight: bold;
        color: #171725;
        margin-bottom: 24px;
    }
    .budget-info-item {
        display: flex;
        margin-bottom: 24px;
        font-size: 14px;
        .label {
            width: 90px;
            padding-right: 16px;
            text-align: right;
            color: #171725;
            flex-shrink: 0;
            font-weight: bold;
        }
        .value {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #44444F;
        }
    }
    
} 
</style>
